上次有介紹到,我們可以用 .ios .android 的檔案名稱後輟來分辨我們是使用 android 還是 ios 的 Component,但是除了這個方法法外,我們偶爾也會因為不同的平台而有一點點小差異,這個時候如果還切一個檔案來負責這個小地方,反而會讓維護的時候非常麻煩,所以 React Native 有提供一個 Platform 它可以拿來辨別這是什麼平台,甚至是版號。
import { Platform } from 'react-native';
const styles = StyleSheet.create({
  height: (Platform.OS === 'ios') ? 200 : 100,
});
我們可以從這個簡單的範例看到 Platform.OS 可以得知目前在運行 app 的是 android 還是 ios 根據這個特性我們就可以來變換他的 style,除了這種簡單的用法我們還能使用 Platform.select
const styles = StyleSheet.create({
  container: {
    flex: 1,
    ...Platform.select({
      ios: {
        backgroundColor: 'red',
      },
      android: {
        backgroundColor: 'blue',
      },
    }),
  },
});
除了 Platform.select、Platform.OS 我們還可以用 Platform.Version 來判端運行的裝置版號
因為偶爾會發生某些版本的 Android 不支援某修功能等等的小地雷,就能用這方式來修復
if(Platform.Version === 21){
  console.log('Running on Lollipop!');
}
有問題歡迎來 React Native Taiwan 問喔
創科資訊